package org.cll.pattern.singleton.exampletwo;


import java.io.File;
import java.io.IOException;
/**
 * @ClassName LoggerExample
 * @Description TODO
 * @Author Administrator
 * @Date 2024-09-10 10:25:47
 * @Version 1.0
 **/
public class LoggerExample {

    public static void main(String[] args) {
        try {
            int numThreads = 100;
            File tempDir = new File("D:\\temp");

            Thread[] threads = new Thread[numThreads];
            Logger[] loggers = new Logger[numThreads];
            TempFileUtils[] tempFileUtils = new TempFileUtils[numThreads];
            for (int i = 0; i < numThreads; i++) {
                TempFileUtils tempFileUtil = new TempFileUtils();
                tempFileUtils[i] = tempFileUtil;
            }

            for (int i = 0; i < numThreads; i++) {
                final int threadId = i;

                threads[i] = new Thread(() -> {
                    try {
                        File tempFile = tempFileUtils[threadId].createTempFile("log", ".txt");
                        loggers[threadId] = new Logger(tempFile);
                        loggers[threadId].log("线程" + threadId + "的日志消息 ");

//                        for (int j = 0; j < 10; j++) {
//                            switch (threadId % 5) {
//                                case 0:
//                                    loggers[0].log("线程" + threadId + "的日志消息 " + j);
//                                    break;
//                                case 1:
//                                    loggers[1].log("线程" + threadId + "的日志消息 " + j);
//                                    break;
//                                case 2:
//                                    loggers[2].log("线程" + threadId + "的日志消息 " + j);
//                                    break;
//                                case 3:
//                                    loggers[3].log("线程" + threadId + "的日志消息 " + j);
//                                    break;
//                                case 4:
//                                    loggers[4].log("线程" + threadId + "的日志消息 " + j);
//                                    break;
//                            }
//                        }
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                threads[i].start();
            }

            for (Thread thread : threads) {
                thread.join();
            }

            for (Logger logger : loggers) {
                logger.close();
            }

            System.out.println("所有线程执行完毕。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

